package cn.easybuy.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.utils.ValidateImage;

import com.alibaba.fastjson.JSON;
@WebServlet("/validate")
public class ValidateServlet extends  HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String type=request.getParameter("type");
		HttpSession session = request.getSession();
		if(type==null){
			response.setContentType("image/png");
			OutputStream os=response.getOutputStream();
			ValidateImage vi=new ValidateImage();
			String viCode=vi.createCode();
			session.setAttribute("code", viCode);
			vi.write(os);
			os.flush();
			os.close();
		} else if(type.equals("yan")){
			String ma=request.getParameter("ma");
			String viCode=(String)session.getAttribute("code");
			boolean flag=false;
			if(ma.toUpperCase().equals(viCode)){
				flag=true;
			} 
			PrintWriter  out=response.getWriter();
			out.print(JSON.toJSONString(flag));
			out.flush();
			out.close();
		}
	}

}
